package com.heima.wemedia.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsService wmNewsService;
    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    GreenScan greenScan;
    @Override
    public void autoScanWmNews(Integer id) {
        // 1 参数校验(id不能为空)
        if (id == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID, "id为空,审核失败");
        }
        // 2 根据id查询文章数据
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "对应文章信息不存在");
        }
        // 3 判断文章状态是否为1(待审核)
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章状态不为待审核,无需审核");
        }

        // 4 提取文章中所有的文本内容和图片内容路径
        Map<String, Object> textAndImages = handleTextAndImages(wmNews);

        // 5 进行自管理敏感词校验
        String content = (String)textAndImages.get("content");
        List<String> images=(List<String>)textAndImages.get("images");
      boolean handleSensitive =handleSensitive(content,wmNews);
      if(!handleSensitive){
        log.info("文章中包含敏感词,审核未通过");
        return;
      }
        //6 进行阿里云内容安全文本审核
        //pass(通过下一步) review(3 人工审核) block(2 失败)
        boolean textScan = handleTextScan(content,wmNews);
      if (!textScan) {
            log.info("文章中包含违规词汇,审核未通过=============");
            return;
        }
        //7 进行阿里云内容安全文本审核
        //pass(通过下一步) review(3 人工审核) block(2 失败)
        if(!CollectionUtils.isEmpty(images)) {
            boolean imageScan = handleImageScan(images, wmNews);
            if (!imageScan) {
                log.info("图片中包含违规,审核未通过=============");
                return;
            }
        }
        // 8 如果全部检测通过,将状态修改为8(通过)
            updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(), "审核通过");
        // 9 发送延时消息,进行文章发布上架操作

    }

    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(), "图片包含违规,审核未通过:"
                            +scanResult.getLabel());
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "图片中包含不确定因素,转为人工审核:" +
                            ""+scanResult.getLabel());
                    break;
                case "pass":
                    break;
                default:
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核异常,转为人工审核");
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核异常,转为人工审核");
        }
        return flag;
    }

    /*
* 调用阿里云文本审核*/
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            //pass(通过下一步) review(3 人工审核) block(2 失败)
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(), "文本包含违规词汇,审核未通过:"
                            +scanResult.getLabel());
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "文本中包含不确定因素,转为人工审核:" +
                            ""+scanResult.getLabel());
                    break;
                case "pass":
                    break;
                default:
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核异常,转为人工审核");
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
            // 转为人工审核
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云审核出现异常,转为人工审核");
        }
        return flag;
    }

    // 敏感词审核
    private boolean handleSensitive(String content, WmNews wmNews) {
        // 1 基于feign远程查询敏感词列表
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if (!sensitives.checkCode()) {
            CustomException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<String> sensitivesData = sensitives.getData();

        // 2 基于DFA算法,封装数据模型
        SensitiveWordUtil.initMap(sensitivesData);
        // 3 基于DFA算法,检测内容是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(CollectionUtils.isEmpty(map)){
        // 4 如果包含敏感词,将文章状态修改为2(审核失败)
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"内容中包含敏感词:"+map);
            return false;
        }
        return true;
    }
        private void updateWmNews(WmNews wmNews,Short status,String reason){
            wmNews.setStatus(status);
            wmNews.setReason(reason);
            wmNewsService.updateById(wmNews);
        }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        List<Map> contentMap = JSON.parseArray(wmNews.getContent(), Map.class);
        // 1 将所有文本内容拼接成一个字符串
        String content = contentMap.stream()
                .filter(m -> "text".equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                //防止上下文本内容拼接引起敏感词
                .collect(Collectors.joining("_hmtt_"));
        content = content + "_hmtt" + wmNews.getTitle();
        // 2 将所有图片路径收集到一个集合中
        List<String> images = contentMap.stream()
                .filter(m -> "image".equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            List<String> coverImages = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            images.addAll(coverImages);
        }
        // 去除重复的图片
        images = images.stream().distinct().collect(Collectors.toList());
        // 3 将内容和路径集合封装到map返回
        Map result = new HashMap();
        result.put("content", content);
        result.put("images", images);
        return result;
    }
}
